<?php
	include_once("dataprovider.php");
	date_default_timezone_set('Asia/Ho_Chi_Minh');
	$action = $_POST["ACTION"];
	session_start();
	if($action == "COMMENT"){
		$userId = isset($_SESSION["loggedUserId"])?$_SESSION["loggedUserId"]:0;//$_POST["userId"];
		$userFullname = $_POST["txtFullname"];
		$article = $_POST["article"];
		$content = $_POST["txtContent"];
		
		//print $userId." " . $userFullname;
		
		$today = date("Y-m-d H:i:s");
		$sql = "insert into comments(userId, fullname, content, createdDate, article, isSpam, active) 
			values(" . $userId . ",'" . $userFullname . "','". $content . "',cast('" . $today . "' as datetime)," . $article . ",0,1)";
		//print $sql;
		$userlst = DataProvider::executeQuery($sql);
		if($userlst != false){
			print "{\"status\":\"OK\"}";
			/*
			if($row = mysql_fetch_array($userlst, MYSQL_ASSOC)){
				$_SESSION["logedUser"] = $row["username"];
				//header("Location: index.php");
			}
			*/
		}else{
			print "{\"status\":\"FAILED\",\"error\":\"". $sql ."\"}";
		}
		//header("Location: ../index.php");
	}else if($action == "LANGUAGE"){
		$article = $_POST["article"];
		$lang = $_POST["language"];
		
		if($lang == 0)
			$userlst = DataProvider::executeQuery("select content_vn as content from articles where id=".$article);
		else
			$userlst = DataProvider::executeQuery("select content_en as content from articles where id=".$article);
			
		if(($userlst != false) && ($row=$userlst->fetch_assoc())){
			//print "{\"status\":\"OK\",\"content\":\"" . stripslashes($row["content"]) . "\"}";
			print stripslashes($row["content"]);
		}else
			print "{\"status\":\"FAILED\"}";
		
	}else if($action == "LOGIN"){
		$user = $_POST["txtUsername"];
		$pass = $_POST["txtPassword"];
		$device = 0;
		if(isset($_POST["DEVICE"])){
			$device = $_POST["DEVICE"];
		}
		$salt = "U" . $pass . "P";
		$pass = sha1($salt);
		
		$loginTime = date("Y-m-d H:i:s");
	
		//$sql = "select id, username from Users where username='{$user}' and hex(pwd)='{$pass}' and active=1";
		$sql = "select id, username from users where username='{$user}' and pwd=X'".$pass."' and active=1";
		//print $sql;
		$sqllog = "insert into user_log(userId, login_time, latitude, longitude, device, token)";
		$userlst = DataProvider::executeQuery($sql);
		if($userlst != false){
			if($row = mysql_fetch_array($userlst, MYSQL_ASSOC)){
				$userId = $row["id"];
				//Generate token for this session
				$token = sha1($loginTime . "-" .$userId);
				$sqllog = "insert into user_log(userId, login_time, latitude, longitude, device, token)
					values(".$userId.", cast('" . $loginTime . "' as datetime), 0, 0, ".$device.",'".$token."');";
				$userlst = DataProvider::executeQuery($sqllog);
				//session_start();
				$_SESSION["loggedUser"] = $row["username"];
				$_SESSION["loggedUserId"] = $userId;
				$_SESSION["token"] = $token;
				//header("Location: ../index.php");
				print "{\"status\":\"OK\"}";
			}else{
				print "{\"status\":\"FAILED\"}";
			}
		}else{
			print "{\"status\":\"FAILED\"}";
		}
		//header("Location: ../index.php");
	}else if($_POST["ACTION"]=="SEARCH"){
		$keyword = $_POST["keyword"];
		$result = DataProvider::executeQuery("select a.id, a.title_vn, a.abstract, u.username, a.createdDate
			from articles as a inner join users as u on a.userId=u.id where a.title_vn like '%" . $keyword . "%' order by a.createdDate desc" );
		if($result != false){
			$jrs = "{\"status\":\"OK\", \"articles\":[";
			$i=0;
			while($row = $result->fetch_assoc()){
				$jrs = $jrs. (($i>0)?",":"") . "{\"id\":\"". $row["id"] ."\",\"title\":\"" . 
					$row["title_vn"] . "\",\"abstract\":\"".$row["abstract"]."\",\"username\":\"".$row["username"]."\",\"datetime\":\"".$row["createdDate"]."\"}";
				$i++;
			}
			
			$jrs = $jrs . "]}";
			print $jrs;
		}else
			print "{\"status\":\"FAILED\"}";
	}
	if($action == "LOGOUT"){
		$logoutTime = date("Y-m-d H:i:s");
		$sqllog = "update user_log set logout_time=cast('" . $logoutTime . "' as datetime) where userId=" . $_SESSION["loggedUserId"] . " and token='" . $_SESSION["token"] . "'";
		DataProvider::executeQuery($sqllog);
		$_SESSION["loggedUser"] = null;
		$_SESSION["loggedUserId"] = null;
		$_SESSION["token"] = null;
		print "{\"status\":\"OK\"}";
	}
?>
